package meng.signature;

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import org.apache.commons.codec.binary.Hex;

public class RSADemo {
	private static String SIGNATURE_ALGORITHM_1 = "MD5withRSA";
	private static String SIGNATURE_ALGORITHM_3 = "SHA1withRSA";

	public static void jdkRSA(String str, String signature_algorithm) {
		try {
			/**
			 * 1.生成密钥对
			 */
			KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
			// 设置长度
			keyPairGenerator.initialize(512);
			KeyPair keyPair = keyPairGenerator.generateKeyPair();
			// 公钥
			RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
			// 私钥
			RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
			System.out.println("公钥:");
			System.out.println(Hex.encodeHexString(rsaPublicKey.getEncoded()));
			System.out.println("私钥:");
			System.out.println(Hex.encodeHexString(rsaPrivateKey.getEncoded()));

			/**
			 * 2.执行签名(私钥加密)
			 */
			PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");// 加密算法RSA
			PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
			Signature signature = Signature.getInstance(signature_algorithm);// 签名算法
			signature.initSign(privateKey);
			signature.update(str.getBytes());
			byte[] bytes = signature.sign();
			System.out.println("原文:" + str);
			System.out.println("数字签名：");
			System.out.println(Hex.encodeHexString(bytes));

			/**
			 * 3. 验证签名(公钥解密)
			 */
			X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded());
			PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
			signature.initVerify(publicKey);
			signature.update(str.getBytes());
			boolean bool = signature.verify(bytes);
			System.out.println(bool);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
